package com.example.javaproject.datastructure.array;

/**
 * Description:
 * <br>Author：tian
 * <br>Time: 2019/3/11 14:49
 */
public class MyArray {
    private int[] intArray;

    //定义数组的实际有效长度
    private int elems;

    //定义数组的最大长度
    private int lenght;

    public MyArray() {
        elems = 0;
        lenght = 50;
        intArray = new int[lenght];
    }

    public MyArray(int lenght) {
        elems = 0;
        this.lenght = lenght;
        intArray = new int[lenght];
    }

    public int getSize() {
        return elems;
    }

    public void dispaly() {
        for (int i = 0; i < elems; i++) {
            System.out.print(intArray[i] + " ");
        }
    }

    public boolean add(int value) {
        //数组已经装满
        if (elems == lenght) {
            return false;
        } else {
            intArray[elems] = value;
            elems++;
            return true;
        }
    }

    public int get(int index) {
        if (index < 0 || index > elems) {
            System.out.println("下班越界");
        }
        return intArray[index];
    }

    public int find(int searchValue) {
        int i;
        for (i = 0; i < elems; i++) {
            if (intArray[i] == searchValue) {
                break;
            }
        }
        if (i == elems) {
            return -1;
        }
        return i;
    }

    public boolean deleteElem(int value) {
        //查询数据是否存在
        int k = find(value);

        if (k == -1) {
            return false;
        } else {

            //如果是删除末位数据
            if (k == elems - 1) {
                elems--;
            } else {
                for (int i = k; i < elems - 1; i++) {
                    intArray[i] = intArray[i + 1];
                }
                elems--;
            }
        }

        return true;
    }

    public boolean modify(int oldValue, int newValue) {
        int k = find(oldValue);
        if (k == -1) {
            return false;
        }

        intArray[k] = newValue;
        return true;
    }

    public static void main(String[] args) {
        //创建自定义封装数组结构，数组大小为4
        MyArray array = new MyArray(4);
        //添加4个元素分别是1,2,3,4
        array.add(1);
        array.add(2);
        array.add(3);
        array.add(4);
        //显示数组元素
        array.dispaly();
        //根据下标为0的元素
        int i = array.get(0);
        System.out.println(i);
        //删除4的元素
        array.deleteElem(4);
        //将元素3修改为33
        array.modify(3, 33);
        array.dispaly();
    }

}
